package com.unlcn.ils.wms.web.controller.excp;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import com.unlcn.ils.wms.backend.bo.excpBO.ExcpFormBO;
import com.unlcn.ils.wms.backend.service.excp.ExcpManageService;
import com.unlcn.ils.wms.backend.util.BrowerEncodeingUtils;
import com.unlcn.ils.wms.web.vo.excp.ExcpFormVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;

/**
 * @Auther linbao
 * @Date 2017-11-21
 * 异常信息管理
 */
@RestController
@RequestMapping("/excpManage")
public class ExcpManageController {

    private Logger LOGGER = LoggerFactory.getLogger(ExcpManageController.class);

    @Autowired
    private ExcpManageService excpManageService;

    /**
     * 分页列表查询
     * <p>
     * 2018-1-30 新需求:异常管理列表查询界面新增车架号/订单号查询
     * </p>
     *
     * @param excpFormVO 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/queryExcepList", method = RequestMethod.POST)
    public ResultDTO<Object> queryExcepList(@RequestBody ExcpFormVO excpFormVO, HttpServletRequest request) {
        LOGGER.info("ExcpManageController.queryExcepList param: {}", excpFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功");
        try {
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            ExcpFormBO excpFormBO = new ExcpFormBO();
            BeanUtils.copyProperties(excpFormVO, excpFormBO);
            excpFormBO.setWhCode(whCode);
            resultDTO.setData(excpManageService.queryExcpListForPage(excpFormBO));
        } catch (BusinessException e) {
            LOGGER.error("ExcpManageController.queryExcepList BusinessException", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("ExcpManageController.queryExcepList error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询失败");
        }
        return resultDTO;
    }

    /**
     * 异常处理
     *
     * @param excpFormVO
     * @return
     */
    @RequestMapping(value = "/updateToDeal", method = RequestMethod.POST)
    public ResultDTO<Object> updateToDeal(@RequestBody ExcpFormVO excpFormVO, HttpServletRequest request) {
        LOGGER.info("ExcpManageController.updateToDeal param: {}", excpFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "异常处理成功");
        try {
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("当前登录用户未绑定仓库");
                return resultDTO;
            }
            ExcpFormBO excpFormBO = new ExcpFormBO();
            BeanUtils.copyProperties(excpFormVO, excpFormBO);
            excpFormBO.setWhCode(whCode);
            excpManageService.updateToDealExcp(excpFormBO);
        } catch (BusinessException e) {
            LOGGER.error("ExcpManageController.updateToDeal BusinessException", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("ExcpManageController.updateToDeal error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("异常处理失败");
        }
        return resultDTO;
    }

    /**
     * 异常关闭
     *
     * @param excpFormVO
     * @return
     */
    @RequestMapping(value = "/updateToClosed", method = RequestMethod.POST)
    public ResultDTO<Object> updateToClosed(@RequestBody ExcpFormVO excpFormVO) {
        LOGGER.info("ExcpManageController.updateToClosed param: {}", excpFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "异常关闭成功");
        try {
            ExcpFormBO excpFormBO = new ExcpFormBO();
            BeanUtils.copyProperties(excpFormVO, excpFormBO);
            excpManageService.updateToCloseExcp(excpFormBO);
        } catch (BusinessException e) {
            LOGGER.error("ExcpManageController.updateToClosed BusinessException", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("ExcpManageController.updateToClosed error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("异常关闭失败");
        }
        return resultDTO;
    }

    /**
     * 获取异常图片列表
     *
     * @param excpFormVO
     * @return
     */
    @RequestMapping(value = "/getImageList", method = RequestMethod.POST)
    public ResultDTO<Object> getImageList(@RequestBody ExcpFormVO excpFormVO) {
        LOGGER.info("ExcpManageController.getImageList param: {}", excpFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "获取异常图片成功");
        try {
            ExcpFormBO excpFormBO = new ExcpFormBO();
            BeanUtils.copyProperties(excpFormVO, excpFormBO);
            resultDTO.setData(excpManageService.getExcpImageList(excpFormBO));
        } catch (BusinessException e) {
            LOGGER.error("ExcpManageController.getImageList BusinessException", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("ExcpManageController.getImageList error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("获取异常图片失败");
        }
        return resultDTO;
    }


    /**
     * 异常列表的导出 --重庆库功能
     * <p>
     * 2018-1-29 异常的列表导出
     * </p>
     *
     * @param excpFormVO 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/importOutExcel", method = RequestMethod.GET)
    public ResultDTO<Object> importOutExcel(ExcpFormVO excpFormVO, HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("ExcpManageController.importOutExcel param: {}", excpFormVO);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "获取异常图片成功");
        //输出流--提供下载
        ServletOutputStream outputStream = null;
        HSSFWorkbook workbook = null;
        BufferedOutputStream bof = null;
        try {
            ExcpFormBO excpFormBO = new ExcpFormBO();
            BeanUtils.copyProperties(excpFormVO, excpFormBO);
            workbook = excpManageService.getImportOutExcel(excpFormBO);
            if (workbook != null) {
                try {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                    response.setHeader("Content-disposition", BrowerEncodeingUtils.getContentDisposition("ExcpManageImportExcel.xls", request));
                    outputStream = response.getOutputStream();
                    bof = new BufferedOutputStream(outputStream);
                    workbook.write(bof);
                } catch (IOException e) {
                    LOGGER.error("WmsInboundAsnServiceImpl.updateInboundImportExcel error:", e);
                    throw new BusinessException("下载文件异常!");
                }
            }
        } catch (BusinessException e) {
            LOGGER.error("ExcpManageController.importOutExcel BusinessException", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("ExcpManageController.importOutExcel error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("导出失败");
        } finally {
            closeResource(bof, outputStream, workbook);
        }
        return resultDTO;
    }

    /**
     * 关闭资源
     *
     * @param outputStream 输出流
     * @param workbook     工作簿
     */
    private void closeResource(BufferedOutputStream bof, ServletOutputStream outputStream, HSSFWorkbook workbook) {
        if (workbook != null) {
            try {
                workbook.close();
            } catch (IOException e) {
                LOGGER.error("workbook.close IOException:", e);
                e.printStackTrace();
            }
        }
        if (bof != null) {
            try {
                bof.flush();
                bof.close();
            } catch (IOException e) {
                LOGGER.error("BufferedOutputStream.close IOException:", e);
                e.printStackTrace();
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                LOGGER.error("outputStream.close IOException:", e);
                e.printStackTrace();
            }
        }

    }

}
